<script setup lang="ts">
import { reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import axios from 'axios'

const router = useRouter()
// 用户注册表单
const registerForm = reactive({
  username: 'ccy',
  password: '111111'
})
let isAgree = ref(false)
let isSame = ref(false)
const confirmPassword = ref('')
const restaurantConfirmPassword = ref('')
// 确认密码一致
const confirmFunc = () => {
  console.log(restaurantForm.password)
  if (!registerForm.password) {
    ElMessage.error('密码不能为空!')
  }
  if (confirmPassword.value !== registerForm.password) {
    isSame.value = false
    console.log(registerForm.password)
    ElMessage.error('密码与确认密码不一致.')
  } else {
    isSame.value = true
  }
}
// 用户注册
function register() {
  console.log('用户注册')
  axios({
    method: 'post',
    url: 'http://localhost:8080/user/register',
    params: {
      username: registerForm.username,
      password: registerForm.password
    }
  }).then(
    (res) => {
      console.log(res.data)
      console.log('正确的')
      ElMessage.success('注册成功')
      router.push('/')
    },
    (err) => {
      console.log('用户注册信息：' + registerForm.username, registerForm.password)
      console.log(err)
      ElMessage.error('注册失败，请刷新后重新填入信息')

      console.log('错误了')
    }
  )
}
function login() {
  router.push('/')
}

// 商家注册表单
const value = ref('')
const restaurantTypeForm = [
  {
    value: '烧烤 ',
    label: '烧烤 '
  },
  {
    value: '地方菜系',
    label: '地方菜系'
  },
  {
    value: '小吃快餐',
    label: '小吃快餐'
  },
  {
    value: '火锅',
    label: '火锅'
  },
  {
    value: '自助餐',
    label: '自助餐'
  },
  {
    value: '面馆',
    label: '面馆'
  },
  {
    value: '咖啡厅',
    label: '咖啡厅'
  },
  {
    value: '面包甜点',
    label: '面包甜点'
  }
]
const restaurantForm = reactive({
  addressareaid: '',
  restauranttypename: '',
  restaurantname: '',
  password: '',
  image: '',
  phone: '',
  introduction: '',
  addressdetail: '',
  surplus: '',
  qualification: ''
})
// 商家确认密码一致
const restaurantConfirmFunc = () => {
  // ElMessage.error("密码不能为空!")
  if (restaurantConfirmPassword.value !== restaurantForm.password) {
    ElMessage.error('密码与确认密码不一致.')
    isSame.value = false
  } else {
    isSame.value = true
  }
}

// 商家注册
function registerRestaurant() {
  axios({
    method: 'post',
    url: 'http://localhost:8080/restaurant/register',
    // 这里的数据要放到params还是data里面
    data: {
      addressareaid: restaurantForm.addressareaid,
      restauranttypename: restaurantForm.restauranttypename,
      restaurantname: restaurantForm.restaurantname,
      password: restaurantForm.password,
      image: restaurantForm.image,
      phone: restaurantForm.phone,
      introduction: restaurantForm.introduction,
      addressdetail: restaurantForm.addressdetail,
      surplus: restaurantForm.surplus,
      qualification: restaurantForm.qualification
    }
  }).then(
    (res) => {
      console.log(res.data)
      console.log('正确的')
      ElMessage.success('注册成功')
      router.push('/')
    },
    (err) => {
      console.log(err)
      ElMessage.success('注册失败,请刷新网页后再注册')
      console.log('错误了')
    }
  )
}

// 上传图片
import { Plus } from '@element-plus/icons-vue'

import type { UploadProps } from 'element-plus'
// 保存图片的临时地址
const imageUrl = ref('')
// 图片上传成功后的回调
const handleRestaurantPictureSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  console.log('上传餐馆照片后回调')

  console.log(response)
  restaurantForm.image = response.data

  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}
// 图片上传前的回调
const beforeRestaurantPicture: UploadProps['beforeUpload'] = (rawFile) => {
  console.log('上传餐馆照片前回调')

  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

// 保存审核图片的临时地址
const imageUrlAudit = ref('')
// 图片上传成功后的回调
const handleAuditQualificationPictureSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  console.log('后回调')
  console.log(response)
  restaurantForm.qualification = response.data

  imageUrlAudit.value = URL.createObjectURL(uploadFile.raw!)
}
// 图片上传前的回调
const beforeAuditQualificationPicture: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}
//管理员注册
function registerManager() {
  axios({
    method: 'post',
    url: 'http://localhost:8080/manage/register',
    params: {
      name: registerForm.username,
      password: registerForm.password
    }
  }).then(
    (res) => {
      console.log(res.data)
      console.log('正确的')
      ElMessage.success('管理员注册成功')
      router.push('/')
    },
    (err) => {
      console.log(err)
      ElMessage.error('注册失败，请刷新后重新填入信息')

      console.log('错误了')
    }
  )
}

// 地区选择器
import { codeToText, regionData } from 'element-china-area-data'
//赋值给级联选择器
const options = ref(regionData)

const selectedOptions = ref([])
const handleChange = () => {
  const str =
    codeToText[selectedOptions.value[0]] +
    '/' +
    codeToText[selectedOptions.value[1]] +
    '/' +
    codeToText[selectedOptions.value[2]]

  restaurantForm.addressareaid = selectedOptions.value[2]
  console.log(restaurantForm.addressareaid)
}
</script>

<template>
  <div class="register">
    <div class="layout">
      <el-tabs type="border-card">
        <!-- 用户注册 -->
        <el-tab-pane label="新用户注册">
          <el-form
            label-position="right"
            label-width="100px"
            style="max-width: 460px"
            class="loginForm"
          >
            <el-form-item label="用户名:" prop="username">
              <el-input v-model="registerForm.username" />
            </el-form-item>
            <el-form-item label="密码:" prop="password">
              <el-input type="password" v-model="registerForm.password" show-password />
            </el-form-item>
            <el-form-item label="确认密码:">
              <el-input
                type="password"
                v-model="confirmPassword"
                @blur="confirmFunc"
                show-password
              />
            </el-form-item>

            <el-row>
              <el-checkbox class="checkBox" v-model="isAgree" label="同意商家使用准则" name="type"
                ><router-link active-class="active" to="/" style="color: #409eff"
                  >同意用户使用准则</router-link
                ></el-checkbox
              >
            </el-row>
            <el-button v-if="isAgree && isSame" type="primary" class="loginBtn" @click="register">
              注册
            </el-button>
            <el-button type="text" class="loginBtn" @click="login"> 返回登录 </el-button>
          </el-form>
        </el-tab-pane>
        <!-- 商家注册 -->
        <el-tab-pane label="商家注册">
          <el-form
            label-position="right"
            label-width="100px"
            style="max-width: 460px"
            class="loginForm"
          >
            <el-form-item label="餐厅地址:" prop="addressareaid" style="width: 300px">
              <div>
                <el-cascader
                  size="default"
                  :options="options"
                  v-model="selectedOptions"
                  @change="handleChange"
                />
              </div>
            </el-form-item>
            <el-form-item label="餐厅类型:" prop="restauranttypename">
              <!-- <el-input v-model="restaurantForm.restauranttypename" /> -->
              <el-select
                v-model="restaurantForm.restauranttypename"
                clearable
                placeholder="Select"
                style="width: 200px"
              >
                <el-option
                  v-for="item in restaurantTypeForm"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="餐厅名称:" prop="restaurantname">
              <el-input v-model="restaurantForm.restaurantname" />
            </el-form-item>
            <el-form-item label="密码:" prop="password">
              <el-input type="password" v-model="restaurantForm.password" show-password />
            </el-form-item>
            <el-form-item label="确认密码:">
              <el-input
                type="password"
                v-model="restaurantConfirmPassword"
                @blur="restaurantConfirmFunc"
                show-password
              />
            </el-form-item>
            <el-form-item label="联系电话:" prop="phone">
              <el-input v-model="restaurantForm.phone" />
            </el-form-item>
            <el-form-item label="餐厅介绍:" prop="introduction">
              <el-input
                v-model="restaurantForm.introduction"
                maxlength="50"
                show-word-limit
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 4 }"
                placeholder="请输入餐厅介绍"
              />
            </el-form-item>
            <el-form-item label="详细地址:" prop="addressdetail">
              <el-input v-model="restaurantForm.addressdetail" />
            </el-form-item>
            <el-form-item label="餐厅容量:" prop="surplus">
              <el-input v-model="restaurantForm.surplus">
                <template #append>餐桌数</template></el-input
              >
            </el-form-item>
            <el-form-item label="餐厅图片:" prop="image">
              <!-- <el-input v-model="restaurantForm.image" /> -->
              <el-upload
                class="avatar-uploader"
                action="http://localhost:8080/data/image"
                :show-file-list="false"
                :on-success="handleRestaurantPictureSuccess"
                :before-upload="beforeRestaurantPicture"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>

            <el-form-item label="审核图片:" prop="image">
              <!-- <el-input v-model="restaurantForm.image" /> -->
              <el-upload
                class="avatar-uploader"
                action="http://localhost:8080/data/image"
                :show-file-list="false"
                :on-success="handleAuditQualificationPictureSuccess"
                :before-upload="beforeAuditQualificationPicture"
              >
                <img v-if="imageUrlAudit" :src="imageUrlAudit" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
            <el-row>
              <el-checkbox class="checkBox" v-model="isAgree" label="同意商家使用准则" name="type"
                ><router-link active-class="active" to="/" style="color: #409eff"
                  >同意商家使用准则</router-link
                ></el-checkbox
              >
            </el-row>
            <el-button
              v-if="isAgree && isSame"
              type="primary"
              class="loginBtn"
              @click="registerRestaurant"
            >
              注册新商家
            </el-button>
            <el-button type="text" class="loginBtn" @click="login"> 返回登录 </el-button>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="管理员注册">
          <el-form
            label-position="right"
            label-width="100px"
            style="max-width: 460px"
            class="loginForm"
          >
            <el-form-item label="用户名:" prop="username">
              <el-input v-model="registerForm.username" />
            </el-form-item>
            <el-form-item label="密码:" prop="password">
              <el-input type="password" v-model="registerForm.password" show-password />
            </el-form-item>
            <el-form-item label="确认密码:">
              <el-input
                type="password"
                v-model="confirmPassword"
                @blur="confirmFunc"
                show-password
              />
            </el-form-item>

            <el-row>
              <el-checkbox class="checkBox" v-model="isAgree" label="同意管理员使用准则" name="type"
                ><router-link active-class="active" to="/" style="color: #409eff"
                  >同意管理员使用准则</router-link
                ></el-checkbox
              >
            </el-row>
            <el-button
              v-if="isAgree && isSame"
              type="primary"
              class="loginBtn"
              @click="registerManager"
            >
              注册
            </el-button>
            <el-button type="text" class="loginBtn" @click="login"> 返回登录 </el-button>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<style lang="scss" scoped>
a {
  text-decoration: none;
}

.router-link-active {
  text-decoration: none;
}

.register {
  // position: absolute;
  // left: calc(50% - 200px);
  // top: 20%;
  // width: 100%;
  // height: 100vh;
  background-color: #dddfe2;

  .layout {
    position: absolute;
    left: calc(50% - 200px);
    top: 20%;
    width: 381px;
  }
}

.loginBtn {
  width: 100px;
  border-radius: 20px;
}

.loginForm {
  text-align: center;
}

.checkBox {
  margin-left: 7px;
}

.inpWidth {
  width: 165px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
